package com.blb.day19_shiro.controller;

import com.blb.day19_shiro.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @PostMapping("/login")
    public String login(Model model, String username, String password){
        //将账号密码交给shiro验证
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            return "index";
        }catch(UnknownAccountException ex){
            model.addAttribute("msg","用户名不存在");
            return "login";
        }catch (IncorrectCredentialsException ex){
            model.addAttribute("msg","密码错误");
            return "login";
        }
    }

//    @RequiresRoles("ceo")
    @RequiresPermissions("user:insert")
    @GetMapping("/hello")
    @ResponseBody
    public String hello(){
        return "hello";
    }
}
